package com.alibaba.cloud.encry;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import org.apache.commons.codec.binary.Hex;


/**
 * The Class DES3.
 *
 * @ClassName: DES3
 * @Description: DES3,同一个密钥进行加密解密处理
 * @author: zhb zhb1316783262@163.com
 * @date: 2018年3月13日 下午5:19:49
 */
public class DES3 {
	
	/** 解密. */
	private static Cipher cipher;
	
	/** 密钥. */
	private static SecretKey secretKey;
	static {
		try {
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
			keyGenerator.init(168);// size
			SecretKey generateKey = keyGenerator.generateKey();
			byte[] keyBytes = generateKey.getEncoded();
			DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(keyBytes);
			secretKey = secretKeyFactory.generateSecret(deSedeKeySpec);
			cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Encode.
	 *
	 * @param src the src
	 * @return the string
	 */
	public String encode(String src) {
		try {
			cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			byte[] resultBytes = cipher.doFinal(src.getBytes());
			return Hex.encodeHexString(resultBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Decode.
	 *
	 * @param src the src
	 * @return the string
	 */
	public String decode(String src) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			byte[] result = Hex.decodeHex(src.toCharArray());
			return new String(cipher.doFinal(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}